#!/usr/bin/perl

use strict;
use DBI;
use CGI;

use Crypt::PasswdMD5 qw(unix_md5_crypt);

# load_log.pl
#  - Jamie Stevens 2010-08-09

# This script loads a particular log, and passes the proper
# information to log_reader.pl.

my $in=CGI->new;

my %inputs=$in->Vars;

# make a webpage for debugging purposes
print $in->header;
print $in->start_html;

# open up a connection to the online_log database
my $dsn="dbi:Pg:dbname=online_log;host=localhost;port=5432";
my $db_user="logadd";
my $db_password="logadd";
my $dbh=DBI->connect($dsn,$db_user,$db_password,
		     {RaiseError => 1, AutoCommit => 1});

# what have we been asked to get?
my $log_id;
my $allow_continue=1;
if ($inputs{"view"}){
    # we must have been asked to load a log from the list
    $log_id=$inputs{"view"};
    # now check for a password
    my $get_password_query="SELECT password FROM log WHERE log_id=".
	$log_id;
    my $get_password=$dbh->prepare($get_password_query);
    $get_password->execute;
    my ($check_password)=$get_password->fetchrow;
    $get_password->finish;

    if ($check_password){
	my $encrypted=unix_md5_crypt($inputs{"psswrd"},
				     $check_password);
	if ($encrypted ne $check_password){
	    print "Incorrect Password!";
	    $allow_continue=0;
	}
    }
}

$dbh->disconnect;

if ($allow_continue==1){
    # now make an invisible form that will get auto submitted, starting
    # the log reader
    print $in->start_form(-name => "return",
			  -method => "post",
			  -action => "log_reader.pl");
    
    print $in->hidden(-name=>"log_id",-default=>$log_id);
    
    print $in->end_form();
    
# now make the bit of Javascript that will auto-submit the form
    print "<script language=\"JavaScript\" type=\"text/javascript\">".
	"document.return.submit();".
	"</script>";
    
    print $in->end_html;

}
